import requests
import json
import logging

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

def fetch_us_stock_news():
    """
    从华尔街见闻API获取美股市场新闻数据并转换为Markdown格式
    """
    api_url = "https://api-one-wscn.awtmt.com/apiv1/content/lives?channel=us-stock-channel&client=pc&limit=20&first_page=true&accept=live%2Cvip-live"
    
    try:
        logger.info("开始请求美股新闻数据: %s", api_url)
        response = requests.get(api_url)
        response.raise_for_status()  # 检查请求是否成功
        logger.info("成功获取API响应，状态码: %d", response.status_code)
        
        data = response.json()
        logger.debug("API响应数据解析成功")
        
        markdown = []
        if 'data' in data and 'items' in data['data']:
            items_count = len(data['data']['items'])
            logger.info("获取到 %d 条新闻数据", items_count)
            
            for index, item in enumerate(data['data']['items'], 1):
                title = item.get('title', '').strip()
                content = item.get('content_text', '').strip()
                
                if title or content:
                    logger.debug("处理第 %d/%d 条新闻", index, items_count)
                    # 如果有标题，使用标题作为二级标题
                    if title:
                        markdown.append(f"## {title}\n")
                    # 添加内容
                    if content:
                        markdown.append(f"{content}\n")
        else:
            logger.warning("API响应数据格式不符合预期")
        
        result = "\n".join(markdown)
        logger.info("新闻数据处理完成，生成的Markdown长度: %d 字符", len(result))
        return result
    except requests.RequestException as e:
        logger.error("获取美股新闻数据时发生网络错误：%s", str(e))
        return ""
    except json.JSONDecodeError as e:
        logger.error("解析API响应数据时发生错误：%s", str(e))
        return ""
    except Exception as e:
        logger.error("处理新闻数据时发生未知错误：%s", str(e))
        return ""

if __name__ == '__main__':
    # 测试函数
    result = fetch_us_stock_news()
    print(result)